import {
  BadRequestException,
  ConflictException,
  Injectable,
  InternalServerErrorException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import {
  AddGoodsTypeDto,
  DelGoodsTypeDto,
  EditGoodsTypeDto,
  GetGoodsTypeByPidDto,
  GetGoodsTypeDto,
} from "../dto/goodsType.dto";
import { GoodsType } from "/@/entities/goods/GoodsType.entity";
import { format } from "/@/utils/moment";
@Injectable()
export class GoodsTypeService {
  constructor(
    private readonly configService: ConfigService,
    @InjectRepository(GoodsType)
    private GoodsTypeRepository: Repository<GoodsType>,
  ) {
    //
  }
  /**
   * 获取商品分类列表
   * @param query 字段
   */
  async getGoodsTypeList(query: GetGoodsTypeDto) {
    const { pageSize = 20, page = 1, name = "", id, pid } = query;
    try {
      let qb = this.GoodsTypeRepository.createQueryBuilder("goodsType");
      qb = qb
        .skip(pageSize * (page - 1))
        .take(pageSize)
        .orderBy("goodsType.update_at", "DESC")
        .where("goodsType.name like :name", { name: "%" + name + "%" });
      if (id) {
        qb = qb.andWhere("goodsType.id = :id", { id });
      }
      if (pid) {
        qb = qb.andWhere("goodsType.pid = :pid", { pid });
      }
      const data = await qb.getManyAndCount();
      const items = data[0].map((item: any) => {
        item.update_at = format(item.update_at, "YYYY-MM-DD HH:mm:ss");
        item.url = item.url.split(",");
        return item;
      });
      return { items, total: data[1] };
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 根据父级id获取商品分类列表-不分页
   * @param query 字段  reverse 是否反选
   */
  async getGoodsTypeListByPid(query: GetGoodsTypeByPidDto) {
    const { pid, reverse = false } = query;
    try {
      let qb = this.GoodsTypeRepository.createQueryBuilder("goodsType");
      qb = qb.orderBy("goodsType.update_at", "DESC");
      if (reverse) {
        qb = qb.where("goodsType.pid != :pid", { pid });
      } else {
        qb = qb.where("goodsType.pid = :pid", { pid });
      }
      const data = await qb.getMany();
      return data;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 添加商品分类
   * @param params 字段
   */
  async addGoodsType(params: AddGoodsTypeDto) {
    const { pid = 0 } = params;
    const goodsType = await this.GoodsTypeRepository.findOne({
      name: params.name,
    });
    if (pid) {
      const pGoodsType = await this.GoodsTypeRepository.findOne({
        id: params.pid,
      });
      params.pname = pGoodsType.name;
    }

    if (goodsType) {
      throw new ConflictException("商品分类名称不可重复");
    }
    //新增商品分类
    const entity = this.GoodsTypeRepository.create(params);
    const result = await this.GoodsTypeRepository.save(entity);
    if (result) {
      return "商品分类创建成功";
    }
  }

  /**
   * 编辑商品分类
   * @param params 字段
   */
  async editGoodsType(params: EditGoodsTypeDto) {
    const { pid = 0, id } = params;

    if (pid === id) {
      throw new BadRequestException("父级不可是自身");
    }

    const goodsType = await this.GoodsTypeRepository.findOne({ id });
    if (!goodsType) {
      throw new BadRequestException("查无此商品分类");
    }

    // 原本是顶级分类的 然后还想改掉这个分类为二级分类
    if (goodsType.pid === 0 && pid !== 0) {
      const pidData = await this.GoodsTypeRepository.findOne({ pid: id });
      if (pidData) {
        throw new BadRequestException(
          "该分类下仍有字商品分类，不可更改为二级分类",
        );
      }
    }

    if (pid) {
      const pGoodsType = await this.GoodsTypeRepository.findOne({
        id: pid,
      });
      params.pname = pGoodsType.name;
    } else {
      params.pname = "无";
    }
    await this.GoodsTypeRepository.update(params.id, params);
    return "ok";
  }

  /**
   * 删除商品分类
   * @param params 字段
   */
  async delGoodsType(params: DelGoodsTypeDto) {
    throw new InternalServerErrorException("未实现");
    return params;
  }
}
